package com.wing.productionPlan.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.entity.ProductionPieceRate;
import com.wing.productionPlan.model.entity.ProductionPieceRateDetail;
import com.wing.productionPlan.model.request.ProductionPieceRateForm;
import com.wing.productionPlan.model.response.ProductionPieceRateDetailVO;
import com.wing.productionPlan.model.response.ProductionPieceRateVO;
import com.wing.productionPlan.service.ProductionPieceRateDetailService;
import com.wing.productionPlan.service.ProductionPieceRateService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.User;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-计件工资单管理", tags = "#/productionPlan/productionPieceRate")
@RestController("productionPieceRateController")
@RequestMapping("productionPlan/admin/productionPieceRate")
@RequiredArgsConstructor
public class ProductionPieceRateController {

    private final ProductionPieceRateService productionPieceRateService;
    private final ProductionPieceRateDetailService pieceRateDetailService;
    private final UserClient userClient;

    
    @ApiOperation(value = "查询所有计件工资单", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProductionPieceRate> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            , Long deptId, Integer month, String code, String theWorkOrderPeopleName
            , String empConfirmTimeStart, String empConfirmTimeEnd, Integer status
            
    ){
        Page<ProductionPieceRate> pg = new Page<>(page, limit);
        QueryWrapper<ProductionPieceRate> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(deptId)) {
            List<User> userList = userClient.getByDepartmentId(deptId);
            if (CollectionUtil.isNotEmpty(userList)){
                List<Long> idList = userList.stream().map(u -> u.getId()).collect(Collectors.toList());
                queryWrapper.in("the_work_order_people", idList);
            }
        }
        if (ObjectUtil.isNotNull(month)) {
            queryWrapper.eq("month", month);
        }
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("code", code);
        }
        if (StringUtils.isNotBlank(theWorkOrderPeopleName)) {
            queryWrapper.like("the_work_order_people_name", theWorkOrderPeopleName);
        }
        if (StringUtils.isNotBlank(empConfirmTimeStart)) {
            queryWrapper.gt("emp_confirm_time", empConfirmTimeStart);
        }
        if (StringUtils.isNotBlank(empConfirmTimeEnd)) {
            queryWrapper.lt("emp_confirm_time", empConfirmTimeEnd);
        }
        if (ObjectUtil.isNotNull(status)) {
            queryWrapper.eq("status", status);
        }
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        
        IPage<ProductionPieceRate> list = productionPieceRateService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加计件工资单", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductionPieceRateForm.Add.class) ProductionPieceRateForm productionPieceRateForm) {
        if (productionPieceRateService.add(productionPieceRateForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改计件工资单", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProductionPieceRateForm.Update.class) ProductionPieceRateForm productionPieceRateForm) {
        ProductionPieceRate productionPieceRate = productionPieceRateService.getById(productionPieceRateForm.getId());
        if(productionPieceRate == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ProductionPieceRate.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productionPieceRateForm, productionPieceRate, copyOptions);
        if (productionPieceRateService.updateById(productionPieceRate)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除计件工资单", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productionPieceRateId", value = "计件工资单id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long productionPieceRateId) {
        if (productionPieceRateService.removeById(productionPieceRateId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查看计件工资详情", notes = "计件工资-详情")
    @GetMapping("detail/{id}")
    public JsonResult<ProductionPieceRateVO> getDetailById(@PathVariable("id") Long id) {
        ProductionPieceRate pieceRate = productionPieceRateService.getById(id);
        ProductionPieceRateVO pieceRateVO = new ProductionPieceRateVO();
        BeanUtil.copyProperties(pieceRate, pieceRateVO);
        if (ObjectUtil.isNotEmpty(pieceRateVO)) {
            QueryWrapper<ProductionPieceRateDetail> pieceRateDetailQueryWrapper = new QueryWrapper<>();
            pieceRateDetailQueryWrapper.eq("piece_rate_id", id);
            List<ProductionPieceRateDetail> pieceRateDetailList = pieceRateDetailService.list(pieceRateDetailQueryWrapper);
            if (CollectionUtil.isNotEmpty(pieceRateDetailList)) {
                List<ProductionPieceRateDetailVO> pieceRateDetailVOList = new ArrayList<>();
                pieceRateDetailList.stream().forEach(p-> {
                    ProductionPieceRateDetailVO pieceRateDetailVO = new ProductionPieceRateDetailVO();
                    BeanUtil.copyProperties(p, pieceRateDetailVO);
                    pieceRateDetailVOList.add(pieceRateDetailVO);
                });
                pieceRateVO.setPieceRateDetailList(pieceRateDetailVOList);
            }
        }
        return JsonResult.success(pieceRateVO);
    }
    
    @ApiOperation(value = "审核计件工资（审核接口）", notes = "审核")
    @PutMapping("/audit/{id}/{status}")
    public JsonResult audit(@PathVariable("id") Long id, @PathVariable("status") String status) {
        Boolean isOk =  productionPieceRateService.audit(id,status);
        if (isOk) {
            return JsonResult.success("审核成功！");

        }
        return JsonResult.fail("审核失败！");
    }

    @ApiOperation(value = "创建计件工资", notes = "计件工资-创建")
    @GetMapping("/create")
    public JsonResult create() {
        Boolean isOk =  productionPieceRateService.create() > 0;
        if (isOk) {
            return JsonResult.success("审核成功！");

        }
        return JsonResult.fail("审核失败！");
    }
    
}
